from settings import settings
from bottle import route, run, get, post, request
# from redis import Redis, ConnectionPool
# import logging
# import traceback
import httplib2
from weibo import APIClient
from instagram.client import InstagramAPI
from six.moves.urllib.parse import urlencode
from json_import import simplejson
# import db
# pool = ConnectionPool(host=settings['redis_ip'], port=settings['redis_port'])

@get('/auth')
def auth_weibo():
    #https://api.weibo.com/oauth2/authorize?redirect_uri=http://p1.junshenwx.com:8000/auth&response_type=code&client_id=3856819567
    query = request.query
    code=query['code']

    print code
    r = client.request_access_token(code)
    access_token = r.access_token
    expires_in = r.expires_in
    print access_token,expires_in
    url = "http://p1.junshenwx.com/kkz/index.php/AppWeb/User/UserRegist?token=%s"%access_token
    return '<meta http-equiv="refresh" content="0; url=%s" />'%url


@get('/auth_instgram')
def auth_instagram():
    #https://api.instagram.com/oauth/authorize/?client_id=98b6258b3d434d31a95ab0eda750db04&redirect_uri=http://p1.junshenwx.com:8000/auth_instgram&response_type=code
    query = request.query
    code=query['code']
    
    print 'code:',code
    access_token = exchange_code_for_access_token(code,api.client_id,api.client_secret,api.redirect_uri)
    print 'access_token',access_token
    url = "http://p1.junshenwx.com/kkz/index.php/AppWeb/User/UserRegist?inst_token=%s"%access_token
    return '<meta http-equiv="refresh" content="0; url=%s" />'%url


def data_for_exchange(code,client_id,client_secret,redirect_uri):
        client_params = {
            "client_id": api.client_id,
            "client_secret": api.client_secret,
            "redirect_uri": api.redirect_uri,
            "grant_type": "authorization_code"
        }
        if code:
            client_params.update(code=code)

        return urlencode(client_params)

def exchange_code_for_access_token(code,client_id,client_secret,redirect_uri):
    data = data_for_exchange(code,client_id,client_secret,redirect_uri)
    print data
    http_object = httplib2.Http()
    url = api.access_token_url

    #put real service outside the greate wall
    url = "https://jilun.me/ins.php"
    print url
    response, content = http_object.request(url, method="POST", body=data)
    print "status code:",response.status
    print 'content:',content
    if response['status']!='200':
        return 'Error'
    else:
        parsed_content = simplejson.loads(content.decode())
        return parsed_content['access_token']

if __name__ == '__main__':
    client = APIClient(settings['APP_KEY'],settings['APP_SECRET'],settings['CALLBACK_URL'])
    api = InstagramAPI(client_id=settings['client_id'], client_secret=settings['client_secret'], redirect_uri=settings['redirect_uri'])
    run(host=settings['server_ip'], port=settings['server_port'])